package com.uvstu.system.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.uvstu.common.core.domain.entity.SysUser;
import com.uvstu.common.utils.DateUtils;
import com.uvstu.common.utils.SecurityUtils;
import com.uvstu.system.domain.NearlyXDays;
import com.uvstu.system.domain.SApplication;
import com.uvstu.system.domain.SStatistics;
import com.uvstu.system.service.ISApplicationService;
import com.uvstu.system.service.ISStatisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.uvstu.system.mapper.SSettlementMapper;
import com.uvstu.system.domain.SSettlement;
import com.uvstu.system.service.ISSettlementService;

/**
 * 结算管理Service业务层处理
 * 
 * @author zwb
 * @date 2023-02-12
 */
@Service
public class SSettlementServiceImpl implements ISSettlementService 
{
    @Autowired
    private SSettlementMapper sSettlementMapper;

    @Autowired
    private ISApplicationService applicationService;

    @Autowired
    private ISStatisticsService isStatisticsService;

    /**
     * 查询结算管理
     * 
     * @param id 结算管理主键
     * @return 结算管理
     */
    @Override
    public SSettlement selectSSettlementById(Long id)
    {
        return sSettlementMapper.selectSSettlementById(id);
    }

    /**
     * 查询结算管理列表
     * 
     * @param sSettlement 结算管理
     * @return 结算管理
     */
    @Override
    public List<SSettlement> selectSSettlementList(SSettlement sSettlement)
    {
        return sSettlementMapper.selectSSettlementList(sSettlement);
    }

    /**
     * 新增结算管理
     * 
     * @param sSettlement 结算管理
     * @return 结果
     */
    @Override
    public int insertSSettlement(SSettlement sSettlement)
    {
        Date date = DateUtils.getNowDate();
        sSettlement.setCreateTime(date);
        sSettlement.setUpdateTime(date);
        return sSettlementMapper.insertSSettlement(sSettlement);
    }

    /**
     * 修改结算管理
     * 
     * @param sSettlement 结算管理
     * @return 结果
     */
    @Override
    public int updateSSettlement(SSettlement sSettlement)
    {
        sSettlement.setUpdateTime(DateUtils.getNowDate());
        return sSettlementMapper.updateSSettlement(sSettlement);
    }

    /**
     * 批量删除结算管理
     * 
     * @param ids 需要删除的结算管理主键
     * @return 结果
     */
    @Override
    public int deleteSSettlementByIds(Long[] ids)
    {
        return sSettlementMapper.deleteSSettlementByIds(ids);
    }

    /**
     * 删除结算管理信息
     * 
     * @param id 结算管理主键
     * @return 结果
     */
    @Override
    public int deleteSSettlementById(Long id)
    {
        return sSettlementMapper.deleteSSettlementById(id);
    }

    /**
     * 查询用户结算信息
     * @param userId
     * @return
     */
    @Override
    public SSettlement selectSSettlementByUserId(Long userId) {
        return sSettlementMapper.selectSSettlementByUserId(userId);
    }

    /**
     * 获取用户结算数据
     * @return
     */
    @Override
    public SSettlement getUserSettlement() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        return sSettlementMapper.selectSSettlementByUserId(user.getUserId());
    }

    /**
     * 更新或新增结算账户
     * @param sSettlement
     * @return
     */
    @Override
    public int updataUserSettlement(SSettlement sSettlement) {
        SSettlement userSettlement = getUserSettlement();
        if(userSettlement == null){
            //新增
            SysUser user = SecurityUtils.getLoginUser().getUser();
            sSettlement.setUserId(user.getUserId());
            sSettlement.setSettlementStatus("1");
            sSettlement.setOneDays("0.00");
            sSettlement.setTowDays("0.00");
            Date date = DateUtils.getNowDate();
            sSettlement.setCreateTime(date);
            sSettlement.setUpdateTime(date);
            return sSettlementMapper.insertSSettlement(sSettlement);
        }else{
            //更新
            userSettlement.setWxImg(sSettlement.getWxImg());
            userSettlement.setZfbImg(sSettlement.getZfbImg());
            Date date = DateUtils.getNowDate();
            userSettlement.setUpdateTime(date);
            return sSettlementMapper.updateSSettlement(userSettlement);
        }
    }

    /**
     * 获取用户基础信息
     * @return
     */
    @Override
    public JSONObject getUserBasicData() {
        JSONObject result = new JSONObject();
        //获取昨天 和 前天结算金额
        SSettlement sSettlement = getUserSettlement();
        if(sSettlement != null){
            result.put("oneDays",sSettlement.getOneDays());
            result.put("towDays",sSettlement.getTowDays());
        }else{
            result.put("oneDays","0.00");
            result.put("towDays","0.00");
        }
        //查询用户名下所有应用
        SysUser user = SecurityUtils.getLoginUser().getUser();
        SApplication sApplication = new SApplication();
        sApplication.setUserId(user.getUserId());
        List<SApplication> sApplicationList = applicationService.selectSApplicationList(sApplication);
        //获取全部统计数据
        List<SStatistics> payList = new ArrayList<>();
        List<SStatistics> refundList = new ArrayList<>();
        for (int i = 0; i < sApplicationList.size(); i++) {
            //获取统计
            SStatistics sStatistics = new SStatistics();
            sStatistics.setAppid(sApplicationList.get(i).getId());
            sStatistics.setType(1L);
            sStatistics = isStatisticsService.getAppIdStatistics(sStatistics);
            if(sStatistics != null){
                payList.add(sStatistics);
            }

            sStatistics = new SStatistics();
            sStatistics.setAppid(sApplicationList.get(i).getId());
            sStatistics.setType(2L);
            sStatistics = isStatisticsService.getAppIdStatistics(sStatistics);
            if(sStatistics != null){
                refundList.add(sStatistics);
            }
        }

        List<NearlyXDays> payArr = new ArrayList<>();
        List<NearlyXDays> refundArr = new ArrayList<>();
        BigDecimal payAmount = new BigDecimal(0);
        BigDecimal refundAmount = new BigDecimal(0);

        Map<String,Double> payMap = new HashMap();
        Map<String,Double> refundMap = new HashMap();

        //支付统计处理
        if(payList.size() != 0){
            for (int i = 0; i < payList.size(); i++) {
                payAmount = payAmount.add(payList.get(i).getTotalAmount());
                //近7天的金额统计
                if(payList.get(i).getNearlyXDays() != null){
                    //处理
                    JSONArray jsonArr = JSONArray.parseArray(payList.get(i).getNearlyXDays());
                    for (int j = 0; j < jsonArr.size(); j++) {
                        JSONObject obj = JSONObject.parseObject(jsonArr.get(j).toString());
                        String time = String.valueOf(obj.get("time"));
                        double amount = 0;
                        if(payMap.get(String.valueOf(obj.get("time"))) != null){
                            try{
                                amount = payMap.get(String.valueOf(obj.get("time")));
                                payMap.put(time,amount+Double.valueOf(String.valueOf(obj.get("amount"))));
                            }catch (Exception e){
                                payMap.put(time,amount);
                            }
                        }else{
                            try{
                                payMap.put(time,Double.valueOf(String.valueOf(obj.get("amount"))));
                            }catch (Exception e){
                                payMap.put(time,amount);
                            }
                        }
                    }
                }
            }
        }
        for (int i = 7; i >= 1; i--) {
            NearlyXDays nearlyXDays = new NearlyXDays();
            nearlyXDays.setTime(getDate(0-i));
            if(payMap.get(getDate(0-i)) == null){
                nearlyXDays.setAmount("0.00");
            }else{
                nearlyXDays.setAmount(String.valueOf(payMap.get(getDate(0-i))));
            }
            payArr.add(nearlyXDays);
        }

        //退款统计处理
        if(refundList.size() != 0){
            for (int i = 0; i < refundList.size(); i++) {
                refundAmount = refundAmount.add(refundList.get(i).getTotalAmount());
                //近7天的退款统计
                if(refundList.get(i).getNearlyXDays() != null){
                    //处理
                    JSONArray jsonArr = JSONArray.parseArray(refundList.get(i).getNearlyXDays());
                    for (int j = 0; j < jsonArr.size(); j++) {
                        JSONObject obj = JSONObject.parseObject(jsonArr.get(j).toString());
                        String time = String.valueOf(obj.get("time"));
                        double amount = 0;
                        if(refundMap.get(String.valueOf(obj.get("time"))) != null){
                            try{
                                amount = refundMap.get(String.valueOf(obj.get("time")));
                                refundMap.put(time,amount+Double.valueOf(String.valueOf(obj.get("amount"))));
                            }catch (Exception e){
                                refundMap.put(time,amount);
                            }
                        }else{
                            try{
                                refundMap.put(time,Double.valueOf(String.valueOf(obj.get("amount"))));
                            }catch (Exception e){
                                refundMap.put(time,amount);
                            }
                        }
                    }
                }
            }
        }
        for (int i = 7; i >= 1; i--) {
            NearlyXDays nearlyXDays = new NearlyXDays();
            nearlyXDays.setTime(getDate(0-i));
            if(refundMap.get(getDate(0-i)) == null){
                nearlyXDays.setAmount("0.00");
            }else{
                nearlyXDays.setAmount(String.valueOf(refundMap.get(getDate(0-i))));
            }
            refundArr.add(nearlyXDays);
        }
        result.put("payAmount",payAmount);
        result.put("refundAmount",refundAmount);
        result.put("payArray",payArr);
        result.put("refundArray",refundArr);
        return result;
    }


    private String getDate(int i) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        //i=-1获取的是前一天  1=1获取的是后一天  1=0获取的是当天
        calendar.add(Calendar.DATE,i);
        return simpleDateFormat.format(calendar.getTime());
    }
}
